<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box{
            width: 100px;
            height: 100px;
            background: pink;
            position: relative;
            left: 0;top: 0;
        }
    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script>
    var box = document.getElementById('box');

    box.onmousedown = function(eve){
        var downE = eve || window.event;
        window.onmousemove = function(eve){
            var e = eve || window.event;
            var l = e.pageX - downE.offsetX;
            var t = e.pageY - downE.offsetY;

            // 边界限定
            if(l < 0){l = 0}    //设置左边为0
            if(t < 0){t = 0}    //设置上边为0

            if(l > document.documentElement.clientWidth - box.offsetWidth){
                l = document.documentElement.clientWidth - box.offsetWidth          //右：浏览器的可视区域的宽度 - 当前元素的宽度
            }
            if(t > document.documentElement.clientHeight - box.offsetHeight){
                t = document.documentElement.clientHeight - box.offsetHeight        //下：浏览器的可视区域的宽度 - 当前元素的宽度
            }

            box.style.left = l + 'px';
            box.style.top = t + 'px';
        }
        window.onmouseup = function(){
            window.onmousemove = null;
        }
    }
</script>
</html>